﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using UpdateG.Config;
using static UpdateG.请在此配置即可;

namespace UpdateG.ViewModel
{
    internal class MainViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged([CallerMemberName] string PropertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
        }
        private ConfigUpdate config;
        public string Logo { get; set; } = Logo路径;
        public string BackImage { get; set; } = 背景图路径;

        private string state;

        public string State
        {
            get { return state; }
            set { state = value; NotifyPropertyChanged(); }
        }

        private long count;

        public long Count
        {
            get { return count; }
            set { count = value; NotifyPropertyChanged(); }
        }

        private long maxValue;


        public long MaxValue
        {
            get { return maxValue; }
            set { maxValue = value; NotifyPropertyChanged(); }
        }

        public MainViewModel()
        {
            config = new ConfigUpdate()
            {
                DesPath = AppDomain.CurrentDomain.BaseDirectory,
                UpdateUrl = 更新地址,
                StartPath = 启动主程序名称,
                ZipName = Path.GetFileName(更新地址),
                VersionUrl = 版本地址
            };

            Task.Run(async () =>
            {
                //是否存在主程序，不存在就更新
                if (File.Exists(config.StartPath))
                {
                    State = "检测版本";
                    MaxValue = 1;

                    string oldVersion = FileVersionInfo.GetVersionInfo(config.StartPath).FileVersion;
                    try
                    {
                        string newVersion = await GetVersion();
                        if (oldVersion != newVersion)
                        {
                            await Update();
                        }
                    }
                    catch (Exception)
                    {
                        State = "网络连接失败";
                        Count++;
                    }

                }
                else
                {
                    await Update();
                }

                try
                {
                    State = "正在进入";
                    await Task.Delay(2000);
                    Process.Start(config.StartPath);
                }
                catch (Exception)
                {
                    State = "未找到对应程序";
                }

                Environment.Exit(0);
            });
        }

        /// <summary>
        /// 更新操作
        /// </summary>
        /// <returns></returns>
        async Task Update()
        {
            State = "开始更新";
            using (Stream stream = await GetStream())
            {
                State = "正在下载";
                MaxValue = stream.Length;
                byte[] buffer = new byte[1024];
                using (FileStream fsWrite = new FileStream(config.ZipName, FileMode.Create, FileAccess.Write))
                {
                    while (true)
                    {
                        int r = stream.Read(buffer, 0, buffer.Length);
                        Count += r;
                        if (r == 0)
                        {
                            break;
                        }
                        await fsWrite.WriteAsync(buffer, 0, r);
                    }
                }
            }
            State = "下载完成";

            DeleteOperation();

            State = "开始安装";
            ZipFile.ExtractToDirectory(config.ZipName, config.DesPath);
            State = "安装完成";
            File.Delete(config.ZipName);
        }

        /// <summary>
        /// 删除当前的所有文件和文件夹
        /// </summary>
        private void DeleteOperation()
        {
            string[] files = Directory.GetFiles(config.DesPath, "*.*", SearchOption.AllDirectories);
            string[] dirs = Directory.GetDirectories(config.DesPath, "*.*", SearchOption.AllDirectories);
            List<string> filesList = files.ToList();
            filesList.Remove($"{config.DesPath}{config.ZipName}");
            foreach (string file in filesList)
            {
                try
                {
                    State = $"正在删除 {file}";
                    File.Delete(file);
                }
                catch (Exception)
                {

                }
            }
            foreach (string dir in dirs)
            {
                try
                {
                    State = $"正在删除 {dir}";
                    Directory.Delete(dir, true);
                }
                catch (Exception)
                {

                }
            }
        }

        /// <summary>
        /// 获取压缩更新包的流
        /// </summary>
        /// <returns></returns>
        async Task<Stream> GetStream()
        {
            HttpRequestMessage req = new HttpRequestMessage(new HttpMethod("GET"), config.UpdateUrl);
            HttpClient http = new HttpClient();
            HttpResponseMessage res = await http.SendAsync(req);
            return await res.Content.ReadAsStreamAsync();
        }

        /// <summary>
        /// 获取版本号
        /// </summary>
        /// <returns></returns>
        async Task<string> GetVersion()
        {
            HttpClient http = new HttpClient();
            return await http.GetStringAsync(config.VersionUrl);
        }
    }
}
